package io.gitee.mingbaobaba.security.starter.endpoint;

import io.gitee.mingbaobaba.security.core.annotion.SecurityIgnore;
import io.gitee.mingbaobaba.security.core.factory.SecurityFactory;
import io.gitee.mingbaobaba.security.core.utils.CaptchaUtil;
import io.gitee.mingbaobaba.security.starter.utils.Base64;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>验证码</p>
 *
 * @author yingsheng.ye
 * @version 1.0.0
 * @since 2023/9/21 15:39
 */
@RestController
@Slf4j
public class CaptchaEndpoint {

    /**
     * 获取验证码
     */
    @SneakyThrows
    @SecurityIgnore
    @GetMapping("/securityCaptcha")
    public Map<String, Object> securityCaptcha() {
        Map<String, Object> result = new HashMap<>();
        //是否开启验证码验证
        result.put("captchaEnabled", SecurityFactory.getConfig.get().getLoginConfig().isCaptchaEnabled());
        String code;
        //是否生成图形验证码
        if (SecurityFactory.getConfig.get().getLoginConfig().isCaptchaGenerateImage()) {
            try {
                FastByteArrayOutputStream os = new FastByteArrayOutputStream();
                code = CaptchaUtil.outputVerifyImage(110, 30, os, 4);
                result.put("img", Base64.encode(os.toByteArray()));
            } catch (Exception e) {
                log.error("生成验证码异常:{}", e.getMessage(), e);
                code = null;
            }
        } else {
            //文字验证码
            code = CaptchaUtil.generateVerifyCode(4);
            result.put("code", code);
        }
        if (Objects.nonNull(code)) {
            String captchaSeqId = SecurityFactory.getSecurityCaptchaRepository.get().saveCaptcha(code, 60 * 5);
            result.put("captchaSeqId", captchaSeqId);
        }
        return result;
    }

}
